package com.zzh.takeoutapp.service;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.webkit.WebSettings;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.model.ModelUtil;
import com.zzh.takeoutapp.utils.NetWorkUtils;
import com.zzh.takeoutapp.utils.S;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class PublicRequest {

    private static NetMsgEvent env;

    public static void doGetRequest(final String url, final Map<String, String> appParams, final Object type) {
        Map<String, String> addMap = new HashMap<>();
        addMap.putAll(appParams);
        OkHttpUtils.get(url).params(addMap).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                NetMsgEvent env = new NetMsgEvent(s);
                env.setMsgType(type);
                EventbusHelper.post(env);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
            }
        });
    }

    public static void postFile(final Context context, String url, final Map<String, String> appParams, List<File> file,
                                final String type) {

        if (isPublicShowToast == false) {
            if (NetWorkUtils.notNetWork(context) == false) {
                isPublicShowToast = true;
            }
        }
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.put("Content-Type", "application/x-www-form-urlencoded");
            OkHttpUtils
                    .post(url)
                    .params(appParams)
                    .headers(httpHeaders)
                    .addFileParams("face", file)
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (isonError == false) {
                                isPublicShowToast = true;
                                env = new NetMsgEvent();
                                env.setFlag(false);
                                env.setMsgType(type);
                                EventbusHelper.post(env);
                            }
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (S.isEmpty(s)) {
                                return;
                            }
                            try {
                                JSONObject object = new JSONObject(s);
                                env = new NetMsgEvent(object);
                                env.setMsgType(type);
                                EventbusHelper.post(env);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
        } catch (Exception r) {
            r.printStackTrace();
        }

    }

    private static String getUserAgent(Context context) {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(context);
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private static boolean isonError = false;
    private static boolean isPublicShowToast = false;

    public static void doPostRequest(final Context context, final String url, final Map<String, String> appParams,
                                     final Object type) {
        if (isPublicShowToast == false) {
            if (NetWorkUtils.notNetWork(context) == false) {
                isPublicShowToast = true;
            }
        }
        try {
            Map<String, String> addMap = new HashMap<>();
            addMap.putAll(appParams);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.put("Content-Type", "application/x-www-form-urlencoded");
            OkHttpUtils.post(url)
                    .tag(type)
                    .params(addMap)
                    .headers(httpHeaders)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (S.isEmpty(s)) {
                                return;
                            }
                            try {
                                JSONObject object = new JSONObject(s);
                                env = new NetMsgEvent(object);
                                env.setMsgType(type);
                                EventbusHelper.post(env);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (isonError == false) {
                                isPublicShowToast = true;
                                env = new NetMsgEvent();
                                env.setFlag(false);
                                env.setMsgType(type);
                                EventbusHelper.post(env);
                            }
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void laodingFile(final Context context) {
        if (NetWorkUtils.notNetWork(context) == false) {
        } else {
            try {
                final ProgressDialog dialog = new ProgressDialog(context);
                dialog.setTitle("正在下载");
                dialog.setCancelable(false);
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                dialog.show();
                OkHttpUtils.get("http://openbox.mobilem.360.cn/index/d/sid/3891273")
                        .execute(new FileCallback(Environment.getExternalStorageDirectory()
                                .getAbsolutePath(), "hsjs_jiagu_sign.apk") {
                            @Override
                            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                                super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                                dialog.setProgress((int) (100 * progress));
                            }

                            @Override
                            public void onSuccess(File file, Call call, Response response) {
                                installApk(context, file);
                                dialog.dismiss();
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 安装apk
     *
     * @param context 上下文
     * @param file    APK文件
     */
    public static void installApk(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  // N以上的申请权限实例
            Uri fileuri = FileProvider.getUriForFile(context, "com.zzh.electricityboardapp.takephoto.fileprovider", file);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(fileuri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        } else {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }

}

